package com.kaiji.mq.send;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 接收消息
 * @author kaiji
 * @since 2018-03-22
 */
public class Receiver {
	private static final Logger __logger = LoggerFactory.getLogger(Receiver.class);
	private static final String USER_NAME = null;
	private static final String PASSWORD = null;
	private static final String TCP = "tcp://localhost:61616";
	public static void main(String[] args) {
		ConnectionFactory cf = new ActiveMQConnectionFactory(USER_NAME, PASSWORD, TCP);
		Connection connection = null;
		try {
			connection = cf.createConnection();
			connection.start();
			
			Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue("kaijiQuene");
			// 创建消息接收者
			MessageConsumer consumer = session.createConsumer(destination);
			
			while(true) {
			// 毫秒为单位 1000 = 1S 设置接收消息的时间为100S
				// 同步接收消息
				TextMessage txt = (TextMessage) consumer.receive(100000);
				if (null == txt) {
					break;
				}
				__logger.info("同步接收到的消息是: {}", txt.getText());
			}
			
			// 异步接收消息
			consumer.setMessageListener(new MessageListener() {
				
				public void onMessage(Message message) {
					TextMessage txt = (TextMessage) message;
					try {
						__logger.info("异步接收到的消息是: {}", txt.getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}
			}) ;
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}
